<template>
	<view class="recycle-search-page">
		<view class="recycle-search-header">
			<uv-search
				v-model="keyword"
				height="30"
				color="#2B2D2E"
				bgColor="#F5F8FA"
				:showAction="false"
				:clearabled="true"
				class="recycle-search-page-search"
				placeholder="输入您的地址"
				@focus="showCancel = true"
			>
				<template #prefix>
					<view class="search-image">
						<image class="icon-search" src="@/static/images/icon_search.png"></image>
					</view>
				</template>
			</uv-search>
			<view
				v-show="showCancel"
				class="cancel-btn"
				@click="cancelSearch"
			>
				取消
			</view>
		</view>
		<view class="recycle-search-body">
			<scroll-view
				scroll-y="true"
				class="recycle-search-scroll-view"
			>
				<view class="recycle-search-scroll-body">
					<view v-show="!showCancel" class="near-address">
						<view class="near-tips">
							<image class="icon-location" src="@/static/images/icon_near_location.png"></image>
							<text>附近的地址</text>
						</view>
						<hsb-business-amap-address
							:list="nearList"
							@choose="checkAddress"
						/>
					</view>
					<view v-show="showCancel" class="search-address">
						<hsb-business-amap-address
							:list="searchList"
							@choose="checkAddress"
						/>
					</view>
				</view>
			</scroll-view>
		</view>
		<hsb-common-base-confirm
			ref="baseConfirmComp"
			content="您当前选择的地址超出上门范围，可选择邮寄回收，是否继续新增？"
			@confirm="confirmAddress"
		/>
	</view>
</template>

<script>
import { mapState } from 'vuex'
import { amapServiceKey } from '@/config'
import debounce from '@climblee/uv-ui/libs/function/debounce.js'
import apis from '@/apis/amap'

export default {
	computed: {
		...mapState({
			userLocation: state => state.userLocation
		})
	},
	data () {
		return {
			recycleWay: '',
			keyword: '',
			nearList: [],
			searchList: [],
			loading: false,
			showCancel: false,
			tempAddress: {}
		}
	},
	watch: {
		keyword (value) {
			if (!value) {
				this.searchList = []
			} else {
				debounce(() => {
					this.getAmapText(value)
				})
			}
		}
	},
	methods: {
		async getAmapAround () {
			if (!this.userLocation.location) return
			const [res] = await apis.getAmapAround({
				key: amapServiceKey,
				offset: 15,
				extensions: 'all',
				location: this.userLocation.location
			})
			if (res.status === '1') {
				this.nearList = this.filterAddressData(res.pois || [])
			}
		},
		async getAmapText (keywords) {
			const [res] = await apis.getAmapText({
				key: amapServiceKey,
				offset: 15,
				extensions: 'all',
				keywords,
				city: '深圳市'
			})
			if (res.status === '1') {
				this.searchList = this.filterAddressData(res.pois || [], keywords)
			}
		},
		async checkAddress (addrInfo) {
			if (this.loading) return
			const { name, pname, cityname, adname, address, location, adcode } = addrInfo
			const [longitude = '', latitude = ''] = location.split(',')
			const pamras = {
				recycleWay: this.recycleWay,
				province: pname,
				city: cityname,
				area: adname,
				areaCode: adcode,
				address,
				longitude,
				latitude
			}
			if (!pamras.recycleWay) {
				return this.chooseAddress({ name, ...pamras })
			}
			this.loading = true
			const [res] = await this.$apis.checkRecycleAddress(pamras)
			this.loading = false
			if (res._errCode === '0') {
				if (res._data.status === '1') {
					return this.chooseAddress({ name, ...pamras })
				}
				this.tempAddress = { name, ...pamras }
				this.$refs.baseConfirmComp.open()
			} else {
				uni.showToast({
					title: res._errStr || '地址校验失败',
					icon: 'none'
				})
			}
		},
		confirmAddress () {
			this.chooseAddress(this.tempAddress)
		},
		chooseAddress (addrInfo) {
			const eventChannel = this.getOpenerEventChannel()
			eventChannel.emit('updateAddressInfo', { data: addrInfo })
			uni.navigateBack()
		},
		filterAddressData (pois, keywords = '') {
			return pois.filter(item => {
				if (
					(!item.location || Array.isArray(item.location)) ||
					(!item.pname || Array.isArray(item.pname)) ||
					(!item.cityname || Array.isArray(item.cityname)) ||
					(!item.adname || Array.isArray(item.adname)) ||
					(!item.address || Array.isArray(item.address))
				) return false
				item.fullNameList = this.assembleKeywords(item, keywords)
				item.distances = ''
				if (typeof item.distance === 'string') {
					if (item.distance > 1000) {
						item.distances = `${(parseFloat(item.distance) / 1000).toFixed(1)}千米`
					} else if (item.distance) {
						item.distances = `${item.distance}米`
					}
				} else {
					if (this.userLocation.location) {
						item.distance = this.computedDistance(this.userLocation.location, item.location)
						if (item.distance > 1000) {
							item.distances = `${(parseFloat(item.distance) / 1000).toFixed(1)}千米`
						} else if (item.distance) {
							item.distances = `${item.distance}米`
						}
					}
				}
				return true
			})
		},
		assembleKeywords (addrInfo, keywords = '') {
			let fullNameList = []
			const filterWord = keywords.trim()
			if (filterWord && addrInfo.name.indexOf(filterWord) !== -1) {
				const start = addrInfo.name.indexOf(filterWord)
				const end = start + filterWord.length
				fullNameList = [
					{ title: addrInfo.name.slice(0, start) || '', isHit: 0 },
					{ title: filterWord, isHit: 1 },
					{ title: addrInfo.name.slice(end) || '', isHit: 0 }
				]
			} else {
				fullNameList = [
					{ title: addrInfo.name || '' }
				]
			}
			return fullNameList
		},
		computedDistance (localPotion, targetPosition) {
		  const long = (Math.PI / 180) * localPotion.split(',')[0]
		  const lat = (Math.PI / 180) * localPotion.split(',')[1]
		  const long2 = (Math.PI / 180) * targetPosition.split(',')[0]
		  const lat2 = (Math.PI / 180) * targetPosition.split(',')[1]
		  const distance = Math.acos(Math.sin(lat) * Math.sin(lat2) + Math.cos(lat) * Math.cos(lat2) * Math.cos(long2 - long)) * 6378
		  return parseInt(distance * 1000)
		},
		cancelSearch () {
			this.showCancel = false
			if (this.keyword) {
				this.keyword = ''
			} else if (this.searchList.length) {
				this.searchList = []
			}
		},
	},
	onLoad (options) {
		this.recycleWay = options.recycleWay
		this.getAmapAround()
	}
}
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
